package io.jft.doll.weidget

import android.app.AlertDialog
import android.databinding.ObservableField
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.View
import com.g.base.ActivityLifecycleHelper
import com.g.base.help.tryCatch
import com.g.base.ui.recyclerView.item.ClickAbleItem
import io.jft.doll.databinding.DialogTimeDownBinding

/**
 * Created by G on 2018/1/1 0001.
 */
class TimeDownDialog(val inflate: LayoutInflater, val title: String, val content: String, val positiveText: String, val negativeText: String, time: Long = 9000L) : ClickAbleItem() {
    val timeObf = ObservableField<String>((time / 1000L).toString() + "s")

    val bind: DialogTimeDownBinding by lazy { DialogTimeDownBinding.inflate(inflate)!! }
    lateinit var dialog: AlertDialog
    private val timer: CountDownTimer = object : CountDownTimer(time, 1000L) {
        override fun onFinish() {
            onClick(bind.negative)
        }

        override fun onTick(p0: Long) {
            timeObf.set((p0 / 1000L).toString() + "s")
        }
    }

    override fun onClick(view: View) {
        timer.cancel()
        tryCatch { dialog.dismiss() }
        super.onClick(view)
    }

    fun start() {
        bind.data = this
        timer.start()
        dialog = AlertDialog.Builder(ActivityLifecycleHelper.getLatestActivity())
                .setCancelable(false)
                .setView(bind.root)
                .show()
    }

}